import os
import ast
import javalang
import subprocess
import json
import vectortransform as v
import TreeBack as t



def identify_file_type(file_path):
    _, ext = os.path.splitext(file_path)
    return ext.lower()


def parse_python_file(file_path):
    with open(file_path, "r", encoding="utf-8") as file:
        source_code = file.read()
    tree = ast.parse(source_code)
    return tree


def parse_java_file(file_path):
    with open(file_path, "r", encoding="utf-8") as file:
        source_code = file.read()
    tree = javalang.parse.parse(source_code)
    return tree


def parse_go_file(file_path):
    # 使用 go/parser 和 go/token 来解析Go文件
    #cmd = f"D:\\python1\\AST\\parser.exe {file_path}"
    cmd = f"E:\\try\\muma\\pythonProject\\parser.exe {file_path}"
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    return json.loads(result.stdout)


def format_python_ast(node, indent=0):
    """格式化Python AST节点"""
    indent_str = ' ' * indent
    result = ""

    if isinstance(node, ast.AST):
        result += f"{indent_str}{type(node).__name__}\n"
        for field in node._fields:
            value = getattr(node, field)
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, ast.AST):
                        result += format_python_ast(item, indent + 2)
                    else:
                        result += f"{indent_str}  {field}: {item}\n"
            elif isinstance(value, ast.AST):
                result += format_python_ast(value, indent + 2)
            else:
                result += f"{indent_str}  {field}: {value}\n"
    return result


def format_java_ast(node, indent=0):
    """格式化Java AST节点"""
    indent_str = ' ' * indent
    result = ""

    if isinstance(node, javalang.tree.CompilationUnit):
        result += f"{indent_str}CompilationUnit\n"
        for class_decl in node.types:
            result += format_java_ast(class_decl, indent + 2)
    elif isinstance(node, javalang.tree.ClassDeclaration):
        result += f"{indent_str}ClassDeclaration: {node.name}\n"
        for method in node.body:
            result += format_java_ast(method, indent + 2)
    elif isinstance(node, javalang.tree.MethodDeclaration):
        result += f"{indent_str}MethodDeclaration: {node.name}\n"
        if node.body:
            for statement in node.body:
                result += format_java_ast(statement, indent + 2)
    elif isinstance(node, javalang.tree.StatementExpression):
        result += f"{indent_str}StatementExpression\n"
        result += format_java_ast(node.expression, indent + 2)
    elif isinstance(node, javalang.tree.MethodInvocation):
        result += f"{indent_str}MethodInvocation: {node.member}\n"
        for arg in node.arguments:
            result += format_java_ast(arg, indent + 2)
    elif isinstance(node, javalang.tree.Literal):
        result += f"{indent_str}Literal: {node.value}\n"
    else:
        result += f"{indent_str}{str(node)}\n"

    return result


def format_go_ast(node, indent=0):
    """格式化Go AST节点"""
    indent_str = ' ' * indent
    result = ""

    if isinstance(node, dict):
        if node.get("type") == "File":
            result += f"{indent_str}File\n"
            for decl in node.get("decls", []):
                result += format_go_ast(decl, indent + 2)
        elif node.get("type") == "GenDecl":
            result += f"{indent_str}GenDecl\n"
            for spec in node.get("specs", []):
                result += format_go_ast(spec, indent + 2)
        elif node.get("type") == "FuncDecl":
            result += f"{indent_str}FuncDecl\n"
            for stmt in node.get("stmts", []):
                result += format_go_ast(stmt, indent + 2)
        elif node.get("type") == "BlockStmt":
            result += f"{indent_str}BlockStmt\n"
            for stmt in node.get("stmts", []):
                result += format_go_ast(stmt, indent + 2)
        elif node.get("type") == "ExprStmt":
            result += f"{indent_str}ExprStmt\n"
            result += format_go_ast({"type": "Literal", "value": node.get("value")}, indent + 2)
        elif node.get("type") == "Literal":
            result += f"{indent_str}Literal: {node.get('value')}\n"
        else:
            result += f"{indent_str}{node}\n"

    return result


def get_ast_tree(tree, file_type):
    if file_type == ".py":
        return format_python_ast(tree)
    elif file_type == ".java":
        return format_java_ast(tree)
    elif file_type == ".go":
        return format_go_ast(tree)
    else:
        return "Eorror,type wrong!"


def get_AST_json(file_path):
    file_type = identify_file_type(file_path)
    # 生成文本形式的tree
    if file_type == ".py":
        tree = parse_python_file(file_path)
    elif file_type == ".java":
        tree = parse_java_file(file_path)
    elif file_type == ".go":
        tree = parse_go_file(file_path)
    else:
        tree=""
        print("Unsupported file type")

    tree=get_ast_tree(tree,file_type)
    file_path = 'data.json'
    # 使用json.dump()将字典写入JSON文件
    with open(file_path, 'w') as json_file:
        json.dump(tree, json_file, indent=4)

    # print(tree)

if __name__ == "__main__":
    path='bot.py'
    get_AST_json(path)

